#include <myheader.h>
#include <sys/epoll.h>
/*Usage:  */
int main(int argc, char *argv[])
{
    int sfd = socket(AF_INET, SOCK_STREAM,0);
    ERROR_CHECK(sfd,-1,"socket");

    //创建sockaddr对象
    struct sockaddr_in client_addr;
    memset(&client_addr, 0, sizeof(client_addr));
    client_addr.sin_addr.s_addr = inet_addr("192.168.112.129");
    client_addr.sin_family = AF_INET;
    client_addr.sin_port = htons(8080);
    int ret = connect(sfd, (struct sockaddr *) &client_addr, sizeof(client_addr));
    ERROR_CHECK(ret, -1, "connect");

    //创建epoll实例
    int efd= epoll_create1(0);
    ERROR_CHECK(efd, -1, "epoll_create1");

    //创建监听对象
    struct epoll_event event;
    event.events = EPOLLIN;
    event.data.fd = STDIN_FILENO;
    ret = epoll_ctl(efd, EPOLL_CTL_ADD, STDIN_FILENO, &event);
    ERROR_CHECK(ret, -1, "eppoll_ctl stdin");
    
    event.events = EPOLLIN;
    event.data.fd = sfd;
    ret = epoll_ctl(efd, EPOLL_CTL_ADD, sfd, &event);
    ERROR_CHECK(ret, -1, "epoll_ctl sfd");

    struct epoll_event events[10];
    int server_exit = 0;
    while(!server_exit)
    {
        int nready = epoll_wait(efd, events, 10, 1000);
        if(nready == -1)
        {
            perror("epoll_wait wrong");
            continue;
        }
        else
        {
            //有数据传送过来
            char buf[1024];
            memset(buf, 0, sizeof(buf));

            for(int i = 0; i < nready; ++i)
            {
                //获取fd
                int fd = events[i].data.fd;
                if(sfd == fd)
                {

                int rec_cnt = recv(fd, &buf, sizeof(buf) - 1, 0);
                ERROR_CHECK(rec_cnt, -1, "recv");
                buf[rec_cnt] = '\0';
                if(rec_cnt == 0)
                {
                    server_exit = 1;
                    printf("server disconnect \n");
                    break;
                }
                printf("%s", buf);
                }
                else
                {
                    //stdin
                    int rec_cnt = read(STDIN_FILENO, buf, sizeof(buf));
                    ERROR_CHECK(rec_cnt, -1,"read");
                    //发送
                    int send_cnt = send(sfd, buf, strlen(buf),0);
                    ERROR_CHECK(send_cnt, -1, "send");
                }

            }
        }
        
    }
    close(sfd);
    close(efd);
    return 0;
}

